<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商品管理系统测试</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
        }

        .header {
            text-align: center;
            color: white;
            margin-bottom: 30px;
        }

        .header h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
        }

        .header p {
            font-size: 1.1rem;
            opacity: 0.9;
        }

        .card {
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            margin-bottom: 20px;
            overflow: hidden;
        }

        .card-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            font-size: 1.3rem;
            font-weight: 600;
        }

        .card-body {
            padding: 20px;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #666;
            font-size: 1.1rem;
        }

        .error {
            background: #fee;
            border: 1px solid #fcc;
            border-radius: 8px;
            padding: 15px;
            color: #c33;
            margin-bottom: 20px;
        }

        .category {
            border: 1px solid #ddd;
            border-radius: 10px;
            margin-bottom: 20px;
            overflow: hidden;
        }

        .category-header {
            background: linear-gradient(135deg, #74b9ff 0%, #0984e3 100%);
            color: white;
            padding: 15px 20px;
            font-weight: 600;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .category-icon {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            object-fit: cover;
            border: 2px solid rgba(255,255,255,0.3);
        }

        .goods-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
            gap: 20px;
            padding: 20px;
            background: #f8f9fa;
        }

        .goods-item {
            background: white;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            transition: transform 0.3s ease, box-shadow 0.3s ease;
            cursor: pointer;
        }

        .goods-item:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
        }

        .goods-image {
            width: 100%;
            height: 200px;
            object-fit: cover;
            background: #f0f0f0;
        }

        .goods-content {
            padding: 15px;
        }

        .goods-name {
            font-size: 1.2rem;
            font-weight: 600;
            color: #333;
            margin-bottom: 8px;
        }

        .goods-price {
            font-size: 1.5rem;
            font-weight: 700;
            color: #e74c3c;
            margin-bottom: 8px;
        }

        .goods-info {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 8px;
            margin-bottom: 10px;
            font-size: 0.9rem;
            color: #666;
        }

        .goods-description {
            color: #666;
            font-size: 0.9rem;
            line-height: 1.4;
            margin-bottom: 10px;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
        }

        .property-list {
            margin-top: 10px;
        }

        .property-item {
            background: #f8f9fa;
            border-radius: 6px;
            padding: 8px;
            margin-bottom: 8px;
        }

        .property-name {
            font-weight: 600;
            color: #495057;
            margin-bottom: 5px;
        }

        .property-values {
            display: flex;
            flex-wrap: wrap;
            gap: 5px;
        }

        .property-value {
            background: #007bff;
            color: white;
            padding: 3px 8px;
            border-radius: 12px;
            font-size: 0.8rem;
        }

        .property-value.default {
            background: #28a745;
        }

        .btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 1rem;
            transition: all 0.3s ease;
            margin: 5px;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102,126,234,0.4);
        }

        .btn-secondary {
            background: linear-gradient(135deg, #6c757d 0%, #495057 100%);
        }

        .btn-danger {
            background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
        }

        .btn-success {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }

        .modal-content {
            background-color: white;
            margin: 5% auto;
            padding: 20px;
            border-radius: 15px;
            width: 90%;
            max-width: 600px;
            max-height: 80vh;
            overflow-y: auto;
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid #eee;
        }

        .close {
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
            color: #999;
        }

        .close:hover {
            color: #333;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: 600;
            color: #333;
        }

        .form-control {
            width: 100%;
            padding: 10px;
            border: 2px solid #ddd;
            border-radius: 8px;
            font-size: 1rem;
            transition: border-color 0.3s ease;
        }

        .form-control:focus {
            outline: none;
            border-color: #667eea;
        }

        .stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }

        .stat-card {
            background: white;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }

        .stat-number {
            font-size: 2rem;
            font-weight: 700;
            color: #667eea;
            margin-bottom: 5px;
        }

        .stat-label {
            color: #666;
            font-size: 0.9rem;
        }

        .action-buttons {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 15px;
            padding-top: 15px;
            border-top: 1px solid #eee;
        }

        @media (max-width: 768px) {
            .goods-grid {
                grid-template-columns: 1fr;
            }
            
            .stats {
                grid-template-columns: repeat(2, 1fr);
            }
            
            .modal-content {
                margin: 10% auto;
                width: 95%;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🛍️ 商品管理系统</h1>
            <p>测试商品数据展示和规格管理功能 (Updated API)</p>
        </div>

        <!-- 统计卡片 -->
        <div class="card">
            <div class="card-header">📊 系统统计</div>
            <div class="card-body">
                <div class="stats" id="stats">
                    <div class="stat-card">
                        <div class="stat-number" id="totalCategories">-</div>
                        <div class="stat-label">商品分类</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number" id="totalGoods">-</div>
                        <div class="stat-label">商品总数</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number" id="totalProperties">-</div>
                        <div class="stat-label">规格总数</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number" id="totalStock">-</div>
                        <div class="stat-label">总库存</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 操作按钮 -->
        <div class="card">
            <div class="card-header">🔧 操作面板</div>
            <div class="card-body">
                <button class="btn" onclick="loadGoods()">🔄 刷新数据</button>
                <button class="btn btn-secondary" onclick="loadTopSales()">🏆 销量排行</button>
                <button class="btn btn-success" onclick="showCreateGoodsModal()">➕ 创建商品</button>
                <button class="btn btn-secondary" onclick="loadProperties()">📐 规格列表</button>
                <button class="btn btn-secondary" onclick="showRawData()">📋 查看原始JSON</button>
                <button class="btn btn-success" onclick="testAPI()">🧪 API测试</button>
            </div>
        </div>

        <!-- 销量排行展示区域 -->
        <div class="card" id="salesRankingCard" style="display: none;">
            <div class="card-header">🏆 销量排行榜（前7名）</div>
            <div class="card-body">
                <div id="salesRankingContainer">
                    <div class="loading">正在加载销量排行数据...</div>
                </div>
            </div>
        </div>

        <!-- 规格列表展示区域 -->
        <div class="card" id="propertiesCard" style="display: none;">
            <div class="card-header">
                <div style="display: flex; justify-content: space-between; align-items: center;">
                    <span>📐 规格列表管理</span>
                    <div>
                        <select id="propertiesGoodsFilter" onchange="loadProperties()">
                            <option value="">全部商品</option>
                        </select>
                        <select id="propertiesCategoryFilter" onchange="loadProperties()">
                            <option value="">全部分类</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div id="propertiesStatsContainer" style="margin-bottom: 20px;"></div>
                <div id="propertiesContainer">
                    <div class="loading">正在加载规格数据...</div>
                </div>
            </div>
        </div>

        <!-- 商品展示区域 -->
        <div class="card">
            <div class="card-header">🛍️ 商品列表</div>
            <div class="card-body">
                <div id="goodsContainer">
                    <div class="loading">正在加载商品数据...</div>
                </div>
            </div>
        </div>
    </div>

    <!-- 商品详情模态框 -->
    <div id="goodsModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="modalTitle">商品详情</h2>
                <span class="close" onclick="closeModal('goodsModal')">&times;</span>
            </div>
            <div id="modalBody"></div>
        </div>
    </div>

    <!-- 规格管理模态框 -->
    <div id="propertyModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>规格管理</h2>
                <span class="close" onclick="closeModal('propertyModal')">&times;</span>
            </div>
            <div id="propertyModalBody"></div>
        </div>
    </div>

    <!-- 原始数据模态框 -->
    <div id="rawDataModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>原始JSON数据</h2>
                <span class="close" onclick="closeModal('rawDataModal')">&times;</span>
            </div>
            <div id="rawDataBody">
                <pre id="rawDataContent" style="background: #f8f9fa; padding: 15px; border-radius: 8px; overflow-x: auto; white-space: pre-wrap;"></pre>
            </div>
        </div>
    </div>

    <!-- 创建商品模态框 -->
    <div id="createGoodsModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2>创建新商品</h2>
                <span class="close" onclick="closeModal('createGoodsModal')">&times;</span>
            </div>
            <div id="createGoodsBody">
                <form id="createGoodsForm" onsubmit="createGoods(event)">
                    <div class="form-group">
                        <label>商品分类 *</label>
                        <select id="categorySelect" class="form-control" required>
                            <option value="">请选择分类</option>
                        </select>
                    </div>
                    
                    <div class="form-group">
                        <label>商品名称 *</label>
                        <input type="text" id="goodsName" class="form-control" required placeholder="请输入商品名称">
                    </div>
                    
                    <div class="form-group">
                        <label>商品价格</label>
                        <input type="number" id="goodsPrice" class="form-control" step="0.01" min="0" placeholder="0.00（可选）">
                    </div>
                    
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                        <div class="form-group">
                            <label>库存数量</label>
                            <input type="number" id="goodsStock" class="form-control" min="0" value="0">
                        </div>
                        
                        <div class="form-group">
                            <label>单位</label>
                            <input type="text" id="goodsUnit" class="form-control" value="件" placeholder="件">
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <label>商品描述</label>
                        <textarea id="goodsContent" class="form-control" rows="3" placeholder="请输入商品描述"></textarea>
                    </div>
                    
                    <div class="form-group">
                        <label>主图地址</label>
                        <input type="url" id="goodsImage" class="form-control" placeholder="https://example.com/image.jpg">
                    </div>
                    
                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px;">
                        <div class="form-group">
                            <label>包装费</label>
                            <input type="number" id="goodsPackCost" class="form-control" step="0.01" min="0" value="0">
                        </div>
                        
                        <div class="form-group">
                            <label>商品类型</label>
                            <select id="goodsType" class="form-control">
                                <option value="1">实物商品</option>
                                <option value="2">虚拟商品</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="form-group">
                        <h4>商品规格设置</h4>
                        <p style="color: #666; font-size: 0.9rem; margin-bottom: 15px;">
                            选择要挂载到此商品的现有规格（可多选）
                        </p>
                        <div id="availablePropertiesContainer" style="max-height: 200px; overflow-y: auto; border: 1px solid #ddd; border-radius: 8px; padding: 10px;">
                            <div class="loading" style="text-align: center; padding: 20px; color: #666;">
                                正在加载可用规格...
                            </div>
                        </div>
                        <button type="button" class="btn btn-secondary" onclick="loadAvailableProperties()" style="margin-top: 10px;">
                            🔄 刷新规格列表
                        </button>
                    </div>
                    
                    <div style="margin-top: 20px; padding-top: 15px; border-top: 1px solid #eee;">
                        <button type="submit" class="btn btn-success">创建商品</button>
                        <button type="button" class="btn btn-secondary" onclick="closeModal('createGoodsModal')">取消</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        let goodsData = [];
        
        // 页面加载时获取数据
        document.addEventListener('DOMContentLoaded', function() {
            loadGoods();
        });

        // 加载商品数据
        async function loadGoods() {
            try {
                const container = document.getElementById('goodsContainer');
                const salesCard = document.getElementById('salesRankingCard');
                container.innerHTML = '<div class="loading">正在加载商品数据...</div>';
                salesCard.style.display = 'none';
                
                const response = await fetch('/api/goods');
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const result = await response.json();
                console.log('API响应:', result);
                
                if (result.code !== 200) {
                    throw new Error(result.message || '获取数据失败');
                }
                
                goodsData = result.data;
                console.log('商品数据:', goodsData);
                
                displayGoods(goodsData);
                updateStats(goodsData);
                loadCategories(); // 加载分类选项
                
            } catch (error) {
                console.error('加载商品数据失败:', error);
                document.getElementById('goodsContainer').innerHTML = 
                    `<div class="error">加载失败: ${error.message}</div>`;
            }
        }

        // 显示商品数据
        function displayGoods(data) {
            const container = document.getElementById('goodsContainer');
            
            if (!data || data.length === 0) {
                container.innerHTML = '<div class="loading">暂无商品数据</div>';
                return;
            }

            let html = '';
            
            data.forEach(category => {
                html += `
                    <div class="category">
                        <div class="category-header">
                            <div>
                                <strong>${category.name}</strong>
                                <span style="opacity: 0.8; margin-left: 10px;">
                                    ${category.goods_list ? category.goods_list.length : 0} 个商品
                                </span>
                            </div>
                            ${category.icon ? `<img src="${category.icon}" alt="分类图标" class="category-icon">` : ''}
                        </div>
                        <div class="goods-grid">
                `;
                
                if (category.goods_list && category.goods_list.length > 0) {
                    category.goods_list.forEach(goods => {
                        const hasProperties = goods.property && goods.property.length > 0;
                        html += `
                            <div class="goods-item" onclick="showGoodsDetail(${goods.id})">
                                <img src="${goods.images || '/placeholder.jpg'}" alt="${goods.name}" class="goods-image" 
                                     onerror="this.src='/placeholder.jpg'">
                                <div class="goods-content">
                                    <div class="goods-name">${goods.name}</div>
                                    <div class="goods-price">¥${goods.price}</div>
                                    <div class="goods-info">
                                        <span>库存: ${goods.stock}</span>
                                        <span>销量: ${goods.sales}</span>
                                        <span>单位: ${goods.unit}</span>
                                        <span>类型: ${goods.goods_type === 1 ? '实物' : '虚拟'}</span>
                                    </div>
                                    <div class="goods-description">${goods.content || '暂无描述'}</div>
                                    ${hasProperties ? renderProperties(goods.property) : ''}
                                    <div class="action-buttons">
                                        <button class="btn" onclick="event.stopPropagation(); showGoodsDetail(${goods.id})">
                                            📄 详情
                                        </button>
                                        ${hasProperties ? `<button class="btn btn-secondary" onclick="event.stopPropagation(); manageProperties(${goods.id})">⚙️ 规格管理</button>` : ''}
                                        <button class="btn btn-danger" onclick="event.stopPropagation(); deleteGoods(${goods.id}, '${goods.name}')">
                                            🗑️ 删除
                                        </button>
                                    </div>
                                </div>
                            </div>
                        `;
                    });
                } else {
                    html += '<div class="loading">该分类暂无商品</div>';
                }
                
                html += `
                        </div>
                    </div>
                `;
            });
            
            container.innerHTML = html;
        }

        // 渲染商品规格 - 更新为使用property_values
        function renderProperties(properties) {
            if (!properties || properties.length === 0) return '';
            
            let html = '<div class="property-list">';
            properties.forEach(prop => {
                html += `
                    <div class="property-item">
                        <div class="property-name">${prop.name}</div>
                        <div class="property-values">
                `;
                
                if (prop.property_values && prop.property_values.length > 0) {
                    prop.property_values.forEach(value => {
                        html += `<span class="property-value ${value.is_default ? 'default' : ''}">${value.value}</span>`;
                    });
                }
                
                html += `
                        </div>
                    </div>
                `;
            });
            html += '</div>';
            
            return html;
        }

        // 更新统计信息
        function updateStats(data) {
            const totalCategories = data.length;
            let totalGoods = 0;
            let totalProperties = 0;
            let totalStock = 0;
            
            data.forEach(category => {
                if (category.goods_list) {
                    totalGoods += category.goods_list.length;
                    category.goods_list.forEach(goods => {
                        totalStock += parseFloat(goods.stock) || 0;
                        if (goods.property) {
                            totalProperties += goods.property.length;
                        }
                    });
                }
            });
            
            document.getElementById('totalCategories').textContent = totalCategories;
            document.getElementById('totalGoods').textContent = totalGoods;
            document.getElementById('totalProperties').textContent = totalProperties;
            document.getElementById('totalStock').textContent = Math.floor(totalStock).toLocaleString();
        }

        // 加载销量排行数据
        async function loadTopSales() {
            try {
                const container = document.getElementById('salesRankingContainer');
                const goodsCard = document.querySelector('.card:has(#goodsContainer)');
                const salesCard = document.getElementById('salesRankingCard');
                
                container.innerHTML = '<div class="loading">正在加载销量排行数据...</div>';
                salesCard.style.display = 'block';
                goodsCard.style.display = 'none';
                
                const response = await fetch('/api/goods/by-sales');
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const result = await response.json();
                console.log('销量排行API响应:', result);
                
                if (result.code !== 200) {
                    throw new Error(result.message || '获取销量排行失败');
                }
                
                const salesData = result.data;
                displaySalesRanking(salesData);
                
            } catch (error) {
                console.error('加载销量排行失败:', error);
                document.getElementById('salesRankingContainer').innerHTML = 
                    `<div class="error">加载失败: ${error.message}</div>`;
            }
        }

        // 显示销量排行
        function displaySalesRanking(data) {
            const container = document.getElementById('salesRankingContainer');
            
            if (!data || data.length === 0) {
                container.innerHTML = '<div class="loading">暂无销量数据</div>';
                return;
            }

            let html = '<div class="goods-grid">';
            
            data.forEach((goods, index) => {
                const rankIcon = index < 3 ? ['🥇', '🥈', '🥉'][index] : `${index + 1}`;
                html += `
                    <div class="goods-item" onclick="showGoodsDetail(${goods.id})">
                        <div style="position: absolute; top: 10px; left: 10px; background: rgba(0,0,0,0.7); color: white; padding: 5px 8px; border-radius: 12px; font-weight: bold;">
                            ${rankIcon}
                        </div>
                        <img src="${goods.images || '/placeholder.jpg'}" alt="${goods.name}" class="goods-image" 
                             onerror="this.src='/placeholder.jpg'">
                        <div class="goods-content">
                            <div class="goods-name">${goods.name}</div>
                            <div class="goods-price">¥${goods.price}</div>
                            <div class="goods-info">
                                <span>🔥 销量: ${goods.sales}</span>
                                <span>📦 库存: ${goods.stock}</span>
                                <span>📂 ${goods.category_name || '未分类'}</span>
                            </div>
                            <div class="goods-description">${goods.content || '暂无描述'}</div>
                            ${goods.property && goods.property.length > 0 ? renderProperties(goods.property) : ''}
                        </div>
                    </div>
                `;
            });
            
            html += '</div>';
            html += '<div style="margin-top: 20px; text-align: center;">';
            html += '<button class="btn" onclick="loadGoods()">返回商品列表</button>';
            html += '</div>';
            
            container.innerHTML = html;
        }

        // 加载分类选项
        async function loadCategories() {
            try {
                if (!goodsData || goodsData.length === 0) return;
                
                const categorySelect = document.getElementById('categorySelect');
                categorySelect.innerHTML = '<option value="">请选择分类</option>';
                
                goodsData.forEach(category => {
                    const option = document.createElement('option');
                    option.value = category.id;
                    option.textContent = category.name;
                    categorySelect.appendChild(option);
                });
                
            } catch (error) {
                console.error('加载分类失败:', error);
            }
        }

        // 显示创建商品模态框
        function showCreateGoodsModal() {
            document.getElementById('createGoodsModal').style.display = 'block';
            loadCategories();
            loadAvailableProperties();
        }

        // 加载可用规格列表
        async function loadAvailableProperties() {
            try {
                const container = document.getElementById('availablePropertiesContainer');
                container.innerHTML = '<div class="loading" style="text-align: center; padding: 20px; color: #666;">正在加载可用规格...</div>';
                
                const response = await fetch('/api/goods-properties');
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const result = await response.json();
                
                if (result.code !== 200) {
                    throw new Error(result.message || '获取规格列表失败');
                }
                
                const properties = result.data || [];
                
                if (properties.length === 0) {
                    container.innerHTML = '<div style="text-align: center; padding: 20px; color: #666;">暂无可用规格</div>';
                    return;
                }
                
                let html = '<div style="display: grid; gap: 10px;">';
                properties.forEach(property => {
                    html += `
                        <label style="display: flex; align-items: center; gap: 10px; padding: 10px; border: 1px solid #eee; border-radius: 6px; cursor: pointer;">
                            <input type="checkbox" name="property_ids" value="${property.id}" style="margin: 0;">
                            <div style="flex: 1;">
                                <div style="font-weight: 600; color: #333;">${property.name}</div>
                                <div style="font-size: 0.85rem; color: #666;">
                                    商品: ${property.goods_name || '未分配'} | 分类: ${property.category_name || '未知'}
                                </div>
                                ${property.desc ? `<div style="font-size: 0.8rem; color: #999; font-style: italic;">${property.desc}</div>` : ''}
                                <div style="margin-top: 5px;">
                                    ${property.property_values && property.property_values.length > 0 ? 
                                        property.property_values.map(value => 
                                            `<span style="background: ${value.is_default ? '#28a745' : '#007bff'}; color: white; padding: 2px 6px; border-radius: 10px; font-size: 0.7rem; margin-right: 3px;">${value.value}</span>`
                                        ).join('') : 
                                        '<span style="color: #999; font-size: 0.8rem;">无规格值</span>'
                                    }
                                </div>
                            </div>
                        </label>
                    `;
                });
                html += '</div>';
                
                container.innerHTML = html;
                
            } catch (error) {
                console.error('加载可用规格失败:', error);
                document.getElementById('availablePropertiesContainer').innerHTML = 
                    `<div style="color: #c33; text-align: center; padding: 20px;">加载失败: ${error.message}</div>`;
            }
        }


        // 创建商品 - 适配新的API格式
        async function createGoods(event) {
            event.preventDefault();
            
            try {
                // 获取选中的规格ID
                const selectedPropertyIds = Array.from(
                    document.querySelectorAll('input[name="property_ids"]:checked')
                ).map(checkbox => parseInt(checkbox.value));
                
                // 获取基本信息
                const goodsData = {
                    category_id: parseInt(document.getElementById('categorySelect').value),
                    name: document.getElementById('goodsName').value,
                    price: parseFloat(document.getElementById('goodsPrice').value) || 0,
                    stock: parseInt(document.getElementById('goodsStock').value) || 0,
                    unit: document.getElementById('goodsUnit').value || '件',
                    content: document.getElementById('goodsContent').value || '',
                    image: document.getElementById('goodsImage').value || '',
                    pack_cost: parseFloat(document.getElementById('goodsPackCost').value) || 0,
                    goods_type: parseInt(document.getElementById('goodsType').value),
                    property_ids: selectedPropertyIds
                };

                console.log('准备创建商品:', goodsData);

                const response = await fetch('/api/goods', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(goodsData)
                });

                const result = await response.json();
                console.log('创建商品响应:', result);

                if (result.code === 201) {
                    alert('商品创建成功！');
                    closeModal('createGoodsModal');
                    document.getElementById('createGoodsForm').reset();
                    // 清除选中的规格
                    document.querySelectorAll('input[name="property_ids"]:checked').forEach(checkbox => {
                        checkbox.checked = false;
                    });
                    loadGoods(); // 刷新商品列表
                } else {
                    alert('创建失败: ' + result.message);
                }

            } catch (error) {
                console.error('创建商品失败:', error);
                alert('创建失败: ' + error.message);
            }
        }

        // 显示商品详情 - 更新为使用property_values
        async function showGoodsDetail(goodsId) {
            try {
                const response = await fetch(`/api/goods/${goodsId}`);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const result = await response.json();
                
                if (result.code !== 200) {
                    throw new Error(result.message || '获取商品详情失败');
                }
                
                const goods = result.data;
                
                const modalBody = document.getElementById('modalBody');
                modalBody.innerHTML = `
                    <div style="display: grid; grid-template-columns: 300px 1fr; gap: 20px;">
                        <div>
                            <img src="${goods.images || '/placeholder.jpg'}" alt="${goods.name}" 
                                 style="width: 100%; border-radius: 10px;" onerror="this.src='/placeholder.jpg'">
                        </div>
                        <div>
                            <h3 style="margin-bottom: 15px; color: #333;">${goods.name}</h3>
                            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-bottom: 15px;">
                                <div><strong>价格:</strong> ¥${goods.price}</div>
                                <div><strong>库存:</strong> ${goods.stock}</div>
                                <div><strong>销量:</strong> ${goods.sales}</div>
                                <div><strong>单位:</strong> ${goods.unit}</div>
                                <div><strong>类型:</strong> ${goods.goods_type === 1 ? '实物商品' : '虚拟商品'}</div>
                                <div><strong>包装费:</strong> ¥${goods.pack_cost}</div>
                            </div>
                            <div style="margin-bottom: 15px;">
                                <strong>商品描述:</strong><br>
                                <p style="margin-top: 5px; line-height: 1.6; color: #666;">${goods.content || '暂无描述'}</p>
                            </div>
                            ${goods.property && goods.property.length > 0 ? renderPropertiesDetail(goods.property) : ''}
                            ${goods.entity && goods.entity.length > 0 ? renderEntitiesDetail(goods.entity) : ''}
                        </div>
                    </div>
                `;
                
                document.getElementById('modalTitle').textContent = `商品详情 - ${goods.name}`;
                document.getElementById('goodsModal').style.display = 'block';
                
            } catch (error) {
                console.error('获取商品详情失败:', error);
                alert('获取商品详情失败: ' + error.message);
            }
        }

        // 渲染详细规格信息 - 更新为使用property_values
        function renderPropertiesDetail(properties) {
            let html = '<div style="margin-bottom: 15px;"><strong>商品规格:</strong>';
            properties.forEach(prop => {
                html += `
                    <div style="background: #f8f9fa; padding: 10px; margin: 10px 0; border-radius: 6px;">
                        <div style="font-weight: 600; margin-bottom: 8px;">${prop.name}</div>
                        <div style="display: flex; flex-wrap: wrap; gap: 5px;">
                `;
                
                if (prop.property_values && prop.property_values.length > 0) {
                    prop.property_values.forEach(value => {
                        html += `<span style="background: ${value.is_default ? '#28a745' : '#007bff'}; color: white; padding: 3px 8px; border-radius: 12px; font-size: 0.8rem;">${value.value}</span>`;
                    });
                }
                
                html += '</div></div>';
            });
            html += '</div>';
            
            return html;
        }

        // 渲染商品实体信息
        function renderEntitiesDetail(entities) {
            let html = '<div><strong>商品实体 (SKU):</strong>';
            entities.forEach(entity => {
                html += `
                    <div style="background: #f8f9fa; padding: 10px; margin: 10px 0; border-radius: 6px;">
                        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 8px; font-size: 0.9rem;">
                            <div><strong>ID:</strong> ${entity.id}</div>
                            <div><strong>价格:</strong> ¥${entity.price}</div>
                            <div><strong>库存:</strong> ${entity.stock}</div>
                            <div><strong>商标:</strong> ${entity.trade_mark || '无'}</div>
                            ${entity.membership_price > 0 ? `<div><strong>会员价:</strong> ¥${entity.membership_price}</div>` : ''}
                        </div>
                    </div>
                `;
            });
            html += '</div>';
            
            return html;
        }

        // 规格管理 - 更新为使用property_values
        function manageProperties(goodsId) {
            const goods = findGoodsById(goodsId);
            if (!goods) {
                alert('商品不存在');
                return;
            }
            
            const modalBody = document.getElementById('propertyModalBody');
            modalBody.innerHTML = `
                <h3 style="margin-bottom: 15px;">${goods.name} - 规格管理</h3>
                <div id="propertiesList"></div>
                <hr style="margin: 20px 0;">
                <h4>添加新规格</h4>
                <div class="form-group">
                    <label>规格名称:</label>
                    <input type="text" id="newPropertyName" class="form-control" placeholder="例如: 温度、尺寸、颜色">
                </div>
                <div class="form-group">
                    <label>规格描述:</label>
                    <input type="text" id="newPropertyDesc" class="form-control" placeholder="可选">
                </div>
                <button class="btn" onclick="addProperty(${goodsId})">添加规格</button>
            `;
            
            renderPropertiesList(goods.property || [], goodsId);
            document.getElementById('propertyModal').style.display = 'block';
        }

        // 渲染规格列表 - 更新为使用property_values
        function renderPropertiesList(properties, goodsId) {
            const container = document.getElementById('propertiesList');
            
            if (!properties || properties.length === 0) {
                container.innerHTML = '<p style="color: #666;">暂无规格，请添加规格</p>';
                return;
            }
            
            let html = '';
            properties.forEach(prop => {
                html += `
                    <div style="border: 1px solid #ddd; border-radius: 8px; padding: 15px; margin-bottom: 15px;">
                        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px;">
                            <h5 style="margin: 0;">${prop.name}</h5>
                            <button class="btn btn-danger" onclick="deleteProperty(${prop.id})">删除</button>
                        </div>
                        ${prop.desc ? `<p style="color: #666; margin-bottom: 10px;">${prop.desc}</p>` : ''}
                        <div style="margin-bottom: 10px;">
                            <strong>规格值:</strong>
                            <div style="display: flex; flex-wrap: wrap; gap: 5px; margin-top: 5px;">
                                ${prop.property_values ? prop.property_values.map(value => 
                                    `<span style="background: ${value.is_default ? '#28a745' : '#007bff'}; color: white; padding: 3px 8px; border-radius: 12px; font-size: 0.8rem;">
                                        ${value.value}
                                        <button onclick="deletePropertyValue(${value.id})" style="background: none; border: none; color: white; margin-left: 5px; cursor: pointer;">×</button>
                                    </span>`
                                ).join('') : ''}
                            </div>
                        </div>
                        <div style="display: flex; gap: 10px; align-items: center;">
                            <input type="text" id="newValue_${prop.id}" placeholder="新规格值" style="flex: 1; padding: 5px; border: 1px solid #ddd; border-radius: 4px;">
                            <label style="display: flex; align-items: center; gap: 5px; font-size: 0.9rem;">
                                <input type="checkbox" id="isDefault_${prop.id}"> 默认值
                            </label>
                            <button class="btn btn-success" onclick="addPropertyValue(${prop.id})">添加值</button>
                        </div>
                    </div>
                `;
            });
            
            container.innerHTML = html;
        }

        // 添加规格（用于已存在的商品）
        async function addProperty(goodsId) {
            const name = document.getElementById('newPropertyName').value.trim();
            const desc = document.getElementById('newPropertyDesc').value.trim();
            
            if (!name) {
                alert('请输入规格名称');
                return;
            }
            
            try {
                const response = await fetch(`/api/goods-properties/${goodsId}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        name: name,
                        desc: desc || null,
                        is_open_checkbox: false
                    })
                });
                
                if (response.ok) {
                    alert('规格添加成功');
                    document.getElementById('newPropertyName').value = '';
                    document.getElementById('newPropertyDesc').value = '';
                    loadGoods(); // 刷新数据
                    closeModal('propertyModal');
                } else {
                    const error = await response.json();
                    alert('添加失败: ' + error.message);
                }
            } catch (error) {
                console.error('添加规格失败:', error);
                alert('添加失败: ' + error.message);
            }
        }

        // 添加规格值
        async function addPropertyValue(propertyId) {
            const value = document.getElementById(`newValue_${propertyId}`).value.trim();
            const isDefault = document.getElementById(`isDefault_${propertyId}`).checked;
            
            if (!value) {
                alert('请输入规格值');
                return;
            }
            
            try {
                const response = await fetch(`/api/goods-properties/${propertyId}/values`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        value: value,
                        code: `CODE_${Date.now()}`, // 生成简单的代码
                        is_default: isDefault
                    })
                });
                
                if (response.ok) {
                    alert('规格值添加成功');
                    loadGoods(); // 刷新数据
                    closeModal('propertyModal');
                } else {
                    const error = await response.json();
                    alert('添加失败: ' + error.message);
                }
            } catch (error) {
                console.error('添加规格值失败:', error);
                alert('添加失败: ' + error.message);
            }
        }

        // 删除规格
        async function deleteProperty(propertyId) {
            if (!confirm('确定要删除这个规格吗？这将同时删除所有相关的规格值。')) {
                return;
            }
            
            try {
                const response = await fetch(`/api/goods-properties/${propertyId}`, {
                    method: 'DELETE'
                });
                
                if (response.ok) {
                    alert('规格删除成功');
                    loadGoods(); // 刷新数据
                    closeModal('propertyModal');
                } else {
                    const error = await response.json();
                    alert('删除失败: ' + error.message);
                }
            } catch (error) {
                console.error('删除规格失败:', error);
                alert('删除失败: ' + error.message);
            }
        }

        // 删除规格值
        async function deletePropertyValue(valueId) {
            if (!confirm('确定要删除这个规格值吗？')) {
                return;
            }
            
            try {
                const response = await fetch(`/api/goods-properties/values/${valueId}`, {
                    method: 'DELETE'
                });
                
                if (response.ok) {
                    alert('规格值删除成功');
                    loadGoods(); // 刷新数据
                    closeModal('propertyModal');
                } else {
                    const error = await response.json();
                    alert('删除失败: ' + error.message);
                }
            } catch (error) {
                console.error('删除规格值失败:', error);
                alert('删除失败: ' + error.message);
            }
        }

        // 显示原始JSON数据
        function showRawData() {
            document.getElementById('rawDataContent').textContent = JSON.stringify(goodsData, null, 2);
            document.getElementById('rawDataModal').style.display = 'block';
        }

        // 加载规格列表数据 - 更新API路径
        async function loadProperties() {
            try {
                const container = document.getElementById('propertiesContainer');
                const statsContainer = document.getElementById('propertiesStatsContainer');
                const goodsCard = document.querySelector('.card:has(#goodsContainer)');
                const salesCard = document.getElementById('salesRankingCard');
                const propertiesCard = document.getElementById('propertiesCard');
                
                container.innerHTML = '<div class="loading">正在加载规格数据...</div>';
                propertiesCard.style.display = 'block';
                goodsCard.style.display = 'none';
                salesCard.style.display = 'none';
                
                // 获取筛选条件
                const goodsId = document.getElementById('propertiesGoodsFilter')?.value || '';
                const categoryId = document.getElementById('propertiesCategoryFilter')?.value || '';
                
                // 构建查询参数
                const params = new URLSearchParams();
                if (goodsId) params.append('goodsId', goodsId);
                if (categoryId) params.append('categoryId', categoryId);
                
                // 同时加载规格数据和统计信息 - 使用新的API路径
                const [propertiesResponse, statsResponse] = await Promise.all([
                    fetch(`/api/goods-properties${params.toString() ? '?' + params.toString() : ''}`),
                    fetch('/api/goods-properties/stats')
                ]);
                
                if (!propertiesResponse.ok || !statsResponse.ok) {
                    throw new Error('获取数据失败');
                }
                
                const propertiesResult = await propertiesResponse.json();
                const statsResult = await statsResponse.json();
                
                console.log('规格数据:', propertiesResult);
                console.log('统计数据:', statsResult);
                
                if (propertiesResult.code !== 200 || statsResult.code !== 200) {
                    throw new Error(propertiesResult.message || statsResult.message || '获取数据失败');
                }
                
                displayPropertiesStats(statsResult.data);
                displayProperties(propertiesResult.data || []);
                loadPropertiesFilters(); // 加载筛选选项
                
            } catch (error) {
                console.error('加载规格数据失败:', error);
                document.getElementById('propertiesContainer').innerHTML = 
                    `<div class="error">加载失败: ${error.message}</div>`;
            }
        }

        // 显示规格统计信息
        function displayPropertiesStats(stats) {
            const container = document.getElementById('propertiesStatsContainer');
            
            const html = `
                <div class="stats">
                    <div class="stat-card">
                        <div class="stat-number">${stats.total_properties || 0}</div>
                        <div class="stat-label">总规格数</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number">${stats.goods_with_properties || 0}</div>
                        <div class="stat-label">有规格商品</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number">${stats.total_property_values || 0}</div>
                        <div class="stat-label">规格值总数</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-number">${stats.categories_with_properties || 0}</div>
                        <div class="stat-label">有规格分类</div>
                    </div>
                </div>
            `;
            
            container.innerHTML = html;
        }

        // 显示规格列表 - 更新为使用property_values
        function displayProperties(properties) {
            const container = document.getElementById('propertiesContainer');
            
            if (!properties || properties.length === 0) {
                container.innerHTML = '<div class="loading">暂无规格数据</div>';
                return;
            }

            let html = '<div style="display: grid; gap: 20px;">';
            
            properties.forEach(property => {
                html += `
                    <div style="border: 1px solid #ddd; border-radius: 10px; overflow: hidden; background: white;">
                        <div style="background: #f8f9fa; padding: 15px; border-bottom: 1px solid #ddd;">
                            <div style="display: flex; justify-content: space-between; align-items: center;">
                                <div>
                                    <h4 style="margin: 0; color: #333;">${property.name}</h4>
                                    <p style="margin: 5px 0 0 0; color: #666; font-size: 0.9rem;">
                                        商品: ${property.goods_name} | 分类: ${property.category_name}
                                    </p>
                                </div>
                                <div style="text-align: right; color: #666; font-size: 0.9rem;">
                                    <div>ID: ${property.id}</div>
                                    <div>${property.is_open_checkbox ? '☑️ 多选' : '◯ 单选'}</div>
                                </div>
                            </div>
                            ${property.desc ? `<p style="margin: 10px 0 0 0; color: #666; font-style: italic;">${property.desc}</p>` : ''}
                        </div>
                        <div style="padding: 15px;">
                            <div style="margin-bottom: 10px;">
                                <strong>规格值 (${property.property_values ? property.property_values.length : 0} 个):</strong>
                            </div>
                            <div style="display: flex; flex-wrap: wrap; gap: 8px;">
                                ${property.property_values && property.property_values.length > 0 ? 
                                    property.property_values.map(value => `
                                        <span style="
                                            background: ${value.is_default ? '#28a745' : '#007bff'}; 
                                            color: white; 
                                            padding: 6px 12px; 
                                            border-radius: 15px; 
                                            font-size: 0.85rem;
                                            display: inline-flex;
                                            align-items: center;
                                            gap: 5px;
                                        ">
                                            ${value.is_default ? '⭐' : ''} ${value.value}
                                            <small style="opacity: 0.8;">[${value.code}]</small>
                                        </span>
                                    `).join('') : 
                                    '<span style="color: #999; font-style: italic;">暂无规格值</span>'
                                }
                            </div>
                        </div>
                    </div>
                `;
            });
            
            html += '</div>';
            html += '<div style="margin-top: 20px; text-align: center;">';
            html += '<button class="btn" onclick="loadGoods()">返回商品列表</button>';
            html += '<button class="btn btn-secondary" onclick="location.reload()">刷新页面</button>';
            html += '</div>';
            
            container.innerHTML = html;
        }

        // 加载规格筛选选项
        function loadPropertiesFilters() {
            if (!goodsData || goodsData.length === 0) return;
            
            // 商品筛选
            const goodsFilter = document.getElementById('propertiesGoodsFilter');
            if (goodsFilter) {
                goodsFilter.innerHTML = '<option value="">全部商品</option>';
                
                goodsData.forEach(category => {
                    if (category.goods_list) {
                        category.goods_list.forEach(goods => {
                            if (goods.property && goods.property.length > 0) {
                                const option = document.createElement('option');
                                option.value = goods.id;
                                option.textContent = `${goods.name} (${category.name})`;
                                goodsFilter.appendChild(option);
                            }
                        });
                    }
                });
            }
            
            // 分类筛选
            const categoryFilter = document.getElementById('propertiesCategoryFilter');
            if (categoryFilter) {
                categoryFilter.innerHTML = '<option value="">全部分类</option>';
                
                goodsData.forEach(category => {
                    const hasPropertiesInCategory = category.goods_list && 
                        category.goods_list.some(goods => goods.property && goods.property.length > 0);
                    
                    if (hasPropertiesInCategory) {
                        const option = document.createElement('option');
                        option.value = category.id;
                        option.textContent = category.name;
                        categoryFilter.appendChild(option);
                    }
                });
            }
        }

        // API测试 - 更新API路径
        async function testAPI() {
            const tests = [
                { name: '获取商品列表', url: '/api/goods' },
                { name: '销量排行榜', url: '/api/goods/by-sales' },
                { name: '获取商品详情', url: '/api/goods/65825' },
                { name: '获取规格列表', url: '/api/goods-properties' },
                { name: '规格统计信息', url: '/api/goods-properties/stats' }
            ];
            
            let results = '🧪 API测试结果:\n\n';
            
            for (const test of tests) {
                try {
                    const start = Date.now();
                    const response = await fetch(test.url);
                    const time = Date.now() - start;
                    
                    if (response.ok) {
                        const result = await response.json();
                        const isSuccess = result.code === 200;
                        results += `${isSuccess ? '✅' : '⚠️'} ${test.name}: ${isSuccess ? '成功' : '警告'} (${time}ms)\n`;
                        results += `   HTTP状态码: ${response.status}\n`;
                        results += `   API响应码: ${result.code}\n`;
                        results += `   消息: ${result.message}\n`;
                        if (result.data) {
                            const dataSize = JSON.stringify(result.data).length;
                            const dataCount = Array.isArray(result.data) ? result.data.length : 1;
                            results += `   数据: ${dataCount} 项, ${dataSize} 字符\n`;
                        }
                        results += '\n';
                    } else {
                        results += `❌ ${test.name}: HTTP失败\n`;
                        results += `   状态码: ${response.status}\n`;
                        results += `   错误: ${response.statusText}\n\n`;
                    }
                } catch (error) {
                    results += `❌ ${test.name}: 网络异常\n`;
                    results += `   错误: ${error.message}\n\n`;
                }
            }
            
            // 测试创建商品API（仅结构验证）
            results += '📝 创建商品API结构:\n';
            results += '   POST /api/goods\n';
            results += '   必需字段: category_id, name\n';
            results += '   可选字段: price, stock, unit, content, image, pack_cost等\n';
            results += '   规格挂载: property_ids数组（挂载现有规格到商品）\n\n';
            
            // 规格查询API说明
            results += '📐 规格查询API:\n';
            results += '   GET /api/goods-properties - 获取规格列表\n';
            results += '   支持参数: ?goodsId=商品ID&categoryId=分类ID\n';
            results += '   GET /api/goods-properties/stats - 规格统计信息\n\n';
            
            alert(results);
        }

        // 通用函数
        function findGoodsById(goodsId) {
            for (const category of goodsData) {
                if (category.goods_list) {
                    const goods = category.goods_list.find(g => g.id === goodsId);
                    if (goods) return goods;
                }
            }
            return null;
        }

        // 删除商品
        async function deleteGoods(goodsId, goodsName) {
            if (!confirm(`确定要删除商品 "${goodsName}" 吗？\n\n注意：删除后将同时删除该商品的所有规格、规格值、实体和图片信息，且不可恢复！`)) {
                return;
            }

            try {
                const response = await fetch(`/api/goods/${goodsId}`, {
                    method: 'DELETE'
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                const result = await response.json();
                
                if (result.code === 200) {
                    alert('商品删除成功！');
                    loadGoods(); // 刷新商品列表
                } else {
                    alert('删除失败: ' + result.message);
                }

            } catch (error) {
                console.error('删除商品失败:', error);
                alert('删除失败: ' + error.message);
            }
        }

        function closeModal(modalId) {
            document.getElementById(modalId).style.display = 'none';
        }

        // 点击模态框外部关闭
        window.onclick = function(event) {
            const modals = ['goodsModal', 'propertyModal', 'rawDataModal', 'createGoodsModal'];
            modals.forEach(modalId => {
                const modal = document.getElementById(modalId);
                if (event.target === modal) {
                    modal.style.display = 'none';
                }
            });
        }
    </script>
</body>
</html>
